<template>
  <div>
    <div style="padding: 5px 0">
      <el-input v-model="text" @keyup.enter.native="load" style="width: 200px"> <i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button @click="add" type="primary" size="mini" style="margin: 10px">新增</el-button>
      <el-button type="success" @click="exportExcel" size="mini" style="margin: 10px">导出</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" id="out-table"  v-loading="loading">
      <el-table-column type="expand">
      <template slot-scope="props">
        <el-card style="margin:0 auto">
          <el-row >
            <el-col :span="8">
              <el-image style="width: 350px; height: 500px" :src="$store.state.imgURLPre+props.row.bookImages" :preview-src-list="[$store.state.imgURLPre+props.row.bookImages]">
            </el-image>
            </el-col>
            <el-col :span="6">
              <p><span style="font-size:30px;margin-left: -20px;">《{{props.row.bookTitle}}》</span></p>
              <p>ISBN码:<span>{{props.row.bookIsbn}}</span></p>
               <p>作者:<span>{{props.row.bookAuthors}}</span></p>
               <p>剩余数量:<span>{{props.row.bookQuantityInput-props.row.bookQuantityOutput}}</span></p>
               <p>价格:<span style="color:orange">￥{{props.row.bookNewPrice}}</span><span style="font-size:15px;color:grey;text-decoration:line-through;margin-left: 5px;">￥{{props.row.bookOldPrice}}</span></p>
                <p>分类:<el-tag type="success" size="50"><span>{{props.row.categoryName}}</span></el-tag></p>
                 <p>出版社:<el-tag type="warning" size="50"><span>{{props.row.publisherName}}</span></el-tag></p>
                  <p>上架状态:<span><el-tag type="success" v-if="props.row.bookState===1" size="50">已上架</el-tag>
          <el-tag type="danger" v-else size="50">已下架</el-tag></span></p>
                  <p>版别:<el-tag  size="50"><span>{{props.row.bookLanguage}}</span></el-tag></p>
                  <p>出版日期:<el-tag type="info" size="50"><span>{{props.row.bookPubDate| dataFomart}}</span></el-tag></p>
            </el-col>
            <el-col :span="8">
              <p>描述：</p>
              <p v-html="props.row.bookDescribe"></p>
            </el-col>
          </el-row>
        </el-card>
      </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="50" sortable> </el-table-column>
      <el-table-column prop="bookTitle" label="图书标题"></el-table-column>
      <el-table-column prop="bookIsbn" label="ISBN码"></el-table-column>
      <el-table-column prop="bookOldPrice" label="原价"></el-table-column>
      <el-table-column prop="bookNewPrice" label="现价"></el-table-column>
      <el-table-column prop="bookImages" label="图书图片" width="120">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="$store.state.imgURLPre+scope.row.bookImages" :preview-src-list="[$store.state.imgURLPre+scope.row.bookImages]">
            </el-image>
            </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类">
        <!-- <template slot-scope="scope">
              {{categorys.filter(e=>e.id===scope.row.categoryId)[0].categoryName}}
            </template> -->
      </el-table-column>
      <el-table-column prop="publisherName" label="出版社" width="180">
        <template slot-scope="scope">
          <el-tag type="warning">{{scope.row.publisherName}}</el-tag>
            </template>
      </el-table-column>
      <el-table-column prop="bookState" label="上架状态">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.bookState===1">已上架</el-tag>
          <el-tag type="danger" v-else>已下架</el-tag>
            </template>
      </el-table-column>
      <el-table-column prop="bookPubDate" label="出版日期" width="100">
        <template slot-scope="scope">
          <el-tag type="info">{{scope.row.bookPubDate | dataFomart  }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="bookAuthors" label="作者"></el-table-column>
      <el-table-column prop="bookLanguage" label="版别">
        <template slot-scope="scope">
          <el-tag>{{scope.row.bookLanguage}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="bookQuantityInput" label="剩余数量">
        <template slot-scope="scope">
          <el-tag type="danger">{{scope.row.bookQuantityInput-scope.row.bookQuantityOutput}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template slot-scope="scope">
          {{scope.row.createTime | dataFomart2  }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间">
        <template slot-scope="scope">
          {{scope.row.updateTime | dataFomart2}}
         </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle  @click="edit(scope.row)"></el-button>
          <el-popconfirm
              @confirm="del(scope.row.id)"
              title="确定删除？"
          >
            <el-button type="danger" icon="el-icon-delete" circle slot="reference" style="margin-left: 10px"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 弹窗   -->
    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="50%" lable-width="100px"
               :close-on-click-modal="false">
      <el-form :model="entity" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="图书标题" label-width="150px" prop="bookTitle">
          <el-input v-model="entity.bookTitle" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="ISBN码" label-width="150px"  prop="bookIsbn">
          <el-input v-model="entity.bookIsbn" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="原价" label-width="150px"  prop="bookOldPrice">
          <el-input v-model="entity.bookOldPrice" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="现价" label-width="150px"  prop="bookNewPrice">
          <el-input v-model="entity.bookNewPrice" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="" label-width="1px" >
          <el-form-item label="文件" label-width="150px">
            <el-upload :action="$store.state.uploadAction" :on-success="fileSuccessUpload" :file-list="fileList"
            list-type="picture">
              <el-button size="small" type="primary">点击上传图片</el-button>
            </el-upload>
          </el-form-item>
          <!-- <el-input v-model="entity.bookImages" autocomplete="off" style="width: 80%"></el-input> -->
        </el-form-item>
        <el-form-item label="描述" label-width="150px" >
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="entity.bookDescribe">
              </quill-editor>
        </el-form-item>
        <el-form-item label="分类" label-width="150px"  prop="categoryId">
          <el-select v-model="entity.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categorys"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出版社" label-width="150px"  prop="publisherId">
          <el-select v-model="entity.publisherId" placeholder="请选择">
            <el-option
              v-for="item in publishers"
              :key="item.id"
              :label="item.publisherName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态" label-width="150px"  prop="bookState">
          <el-radio v-model="entity.bookState" label="1">上架</el-radio>
          <el-radio v-model="entity.bookState" label="0">下架</el-radio>
          <!-- <el-input v-model="entity.bookState" autocomplete="off" style="width: 80%"></el-input> -->
        </el-form-item>
        <el-form-item label="出版日期" label-width="150px"  prop="bookPubDate">
          <el-date-picker type="date" placeholder="选择日期" v-model="entity.bookPubDate" style="width: 80%" value-format="yyyy-MM-dd"></el-date-picker>
          <!-- <el-date-picker style="width: 80%" v-model="entity.bookPubDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker> -->
        </el-form-item>
        
        <el-form-item label="作者" label-width="150px"  prop="bookAuthors">
          <el-input v-model="entity.bookAuthors" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="版别" label-width="150px">
          <el-input v-model="entity.bookLanguage" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="入库数量" label-width="150px" prop="bookQuantityInput">
          <el-input v-model.number="entity.bookQuantityInput" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        
        

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import API from '../../utils/request'
const url = "/api/msslyyBook/"
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  name: "MsslyyBook",
  data() {
    var checkmoney = (rule, value, cb) => {
        // 数字或小数的正则表达式
        const regmoney = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,2})$)|^(([1-9]+)$)/

        if (regmoney.test(value)) {
          return cb()
        }

        cb(new Error('请输入正确的价格'))
      }
    return {
      loading:true,
      fileList: [],
      options: [],
      text: '',
      user: {},
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      entity: {},
      total: 0,
      dialogFormVisible: false,
      addFormRules:{
        bookQuantityOutput:[
        { required: true, message: '请输入出库数量', trigger: 'blur' },
        { type: 'number', message: '出库数量必须为数字值'}
        ],
        bookQuantityInput:[
        { required: true, message: '请输入入库数量', trigger: 'blur' },
        { type: 'number', message: '入库数量必须为数字值'}
        ],
        bookTitle:[
        { required: true, message: '请输入图书标题', trigger: 'blur' }
        ],
        bookIsbn:[
        { required: true, message: '请输入ISBN码', trigger: 'blur' },
      
       
        ],
        bookOldPrice:[
        { required: true, message: '请输入原价', trigger: 'blur' },
        { validator: checkmoney, trigger: 'blur' }
       
        ],
        bookNewPrice:[
        { required: true, message: '请输入现价', trigger: 'blur' },
        { validator: checkmoney, trigger: 'blur' }
       
        ],
        categoryId:[
        { required: true, message: '请输入分类ID', trigger: 'blur' },
        { type: 'number', message: '分类ID必须为数字值'}
       
        ],
        publisherId:[
        { required: true, message: '请输入出版社ID', trigger: 'blur' },
        { type: 'number', message: '出版社ID必须为数字值'}
       
        ],
       
        
        bookPubDate:[
        { required: true, message: '请输入出版日期', trigger: 'blur' },
       
        ],
        bookAuthors:[
        { required: true, message: '请输入作者', trigger: 'blur' },
       
        ],
      
        
      },
      categorys:[],
      publishers:[],
    };
  },
  filters:{
    
    
    dataFomart(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>10?dt.getDate():"0"+dt.getDate(); 
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}`
    },
    dataFomart2(date){
      
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>=10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>=10?dt.getDate():"0"+dt.getDate(); 
       let hh=dt.getHours()>=10?dt.getHours():"0"+dt.getHours();
       let mm=dt.getMinutes()>=10?dt.getMinutes():"0"+dt.getMinutes();
       let ss=dt.getSeconds()>=10?dt.getSeconds():"0"+dt.getSeconds();
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}  ${hh}:${mm}:${ss}`
    }
      },
  created() {
    this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
    this.$emit('user', this.user);
    this.load()
    
  },
  methods: {
    getAllCategory(){
      API.get('/api/msslyyCategory').then(res => {
          if (res.code === '0') {
             this.categorys=res.data
             console.log(this.categorys);
           }
       })
    },
    getAllPublisher(){
      API.get('/api/msslyyPublisher').then(res => {
          if (res.code === '0') {
             this.publishers=res.data
             console.log(this.publishers);
           }
       })
    },
    //图片
  fileSuccessUpload(res) {
      this.entity.bookImages =  res.data;
      this.fileList = [res.data]
      console.log(res)
     
    },
    exportExcel () {
   var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
   var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
   try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.$options.name+'.xlsx')
   } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
   return wbout
  },
 
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    load() {
       API.get(url + "/page", {
          params: {
            publisherId:0,
            categoryId:0,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.text
          }
       }).then(res => {
          this.getAllCategory()
          this.getAllPublisher()
          this.tableData = res.data.records || []
          this.loading=false
          this.total = res.data.total
       })
    },
    add() {
      this.entity = {}
      this.fileList = []
      this.dialogFormVisible = true
    },
    edit(obj) {
      this.entity = JSON.parse(JSON.stringify(obj))
      this.fileList = []
      this.dialogFormVisible = true
      console.log(this.entity);
    },
    save() {
      this.$refs.addFormRef.validate(async valid => {
          console.log(valid);
          if (!valid) return
          if (!this.entity.id) {
        API.post(url, this.entity).then(res => {
           if (res.code === '0') {
             this.$message({
               type: "success",
               message: "操作成功"
             })
           } else {
             this.$message({
               type: "error",
               message: res.msg
             })
           }
           this.load()
           this.dialogFormVisible = false
        })
      } else {
        API.put(url, this.entity).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "操作成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()
          this.dialogFormVisible = false
        })
      }
        
        })
   
    },
    del(id) {
      API.delete(url + id).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        })
        this.load()
      })
    }
  },
};
</script>

<style scoped>
.el-col p{
  font-size: 20px;
}
.el-col p>span{
  margin-left: 20px;
}
</style>
